//
//  CarInputSecondVC.m
//  New_Runway
//
//  Created by mack on 2018/2/6.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarInputSecondVC.h"
#import "PickCustomView.h"
#import "CarSetListCell.h"
#import "CarPictureSubmitVC.h"
#import "CarConfigChooseVC.h"
#import "IamgeFactory.h"
#import "CarDetailMainVC.h"
#import "GetCarConfModel.h"
#import "CrmIsArriveShopCell.h"
#import "UserModel.h"


@interface CarInputSecondVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,CustomPickViewDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *configIds;
@property (nonatomic, strong) NSMutableArray *configNames;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic , assign) NSInteger carExtendedWarranty;
@property (nonatomic , assign) NSInteger carFinanceService;
@property (nonatomic, copy) NSString *saleUserId;
@property (nonatomic, strong) NSMutableArray *userArray;
@end

@implementation CarInputSecondVC
{
    
    BOOL is4S;
    NSString *_flawDesc;
    NSString *_sellingPointDesc;
//    NSString *_mortgageDesc;
    NSString *_staffName;
    
}
-(NSMutableArray *)userArray{
    if (!_userArray) {
        _userArray = [[NSMutableArray alloc] init];
    }
    return _userArray;
}
-(NSMutableArray *)listArray{
    if (!_listArray) {
        _listArray = [[NSMutableArray alloc] init];
    }
    return _listArray;
}
-(NSMutableArray *)configIds{
    
    if (!_configIds) {
        _configIds = [[NSMutableArray alloc] init];
    }
    return _configIds;
}
-(NSMutableArray *)configNames{
    if (!_configNames) {
        _configNames = [[NSMutableArray alloc] init];
    }
    
    return _configNames;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"更多信息";
    self.view.backgroundColor = kColorWhite();
    [self.navigationBarView.rightItem setTitle:@"确定" forState:UIControlStateNormal];
    [self initTableview];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    is4S = NO;
     _flawDesc = _sellingPointDesc  = @"";
    _carExtendedWarranty = _carFinanceService = 0;
    _saleUserId = @"";
    [self loadCarConfigInfo];
    
}

-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerClass:[CarSetListCell class] forCellReuseIdentifier:@"CarSetListCell"];
        [self.view addSubview:self.tableview];
    [self.tableview registerNib:[UINib nibWithNibName:@"CrmIsArriveShopCell" bundle:nil] forCellReuseIdentifier:@"CrmIsArriveShopCell"];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 45;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *array = @[@"上传图片",@"环保标准",@"车辆配置",@"燃油类型",@"是否4S店保养",@"瑕疵描述",@"卖点描述",@"金融服务",@"延保服务",@"销售人员"];
    if (indexPath.row == 7 ) {
        CrmIsArriveShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrmIsArriveShopCell"];
        cell.mianLabel.text = array[indexPath.row];
        cell.index = indexPath;
        if (self.carFinanceService == 1) {
            [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateNormal];
            [cell.isYesB setTitleColor:MAIN_NAV_COLOR() forState:UIControlStateNormal];
            [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
            [cell.isNoB setTitleColor:MAIN_FONT_COLOR() forState:UIControlStateNormal];
        }else{
            [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
            [cell.isYesB setTitleColor:MAIN_FONT_COLOR() forState:UIControlStateNormal];
            [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateNormal];
            [cell.isNoB setTitleColor:MAIN_NAV_COLOR() forState:UIControlStateNormal];
            
        }
        return cell;
    }else if (indexPath.row == 8){
        CrmIsArriveShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrmIsArriveShopCell"];
        cell.mianLabel.text = array[indexPath.row];
        cell.index = indexPath;
        if (self.carExtendedWarranty == 1) {
            [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateNormal];
            [cell.isYesB setTitleColor:MAIN_NAV_COLOR() forState:UIControlStateNormal];
            [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
            [cell.isNoB setTitleColor:MAIN_FONT_COLOR() forState:UIControlStateNormal];
        }else{
            [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
            [cell.isYesB setTitleColor:MAIN_FONT_COLOR() forState:UIControlStateNormal];
            [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateNormal];
            [cell.isNoB setTitleColor:MAIN_NAV_COLOR() forState:UIControlStateNormal];
            
        }
        return cell;
    }
    
    CarSetListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarSetListCell"];
    cell.label.text  = array[indexPath.row];
    cell.centerTF.tag = indexPath.row;
    cell.switchButton.hidden = YES;
    cell.centerLabel.hidden = YES;
    cell.centerTF.delegate = self;
    cell.centerTF.keyboardType = UIKeyboardTypeDefault;
    cell.rightImage.hidden = NO;
    [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
    [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
    cell.centerTF.userInteractionEnabled = NO;
    cell.picImage.hidden = YES;
    cell.centerTF.tag = indexPath.row;
    cell.StarL.hidden = YES;

    
    if (indexPath.row == 0) {
        cell.picImage.hidden = NO;
        cell.centerTF.hidden = YES;
        cell.StarL.hidden = NO;

        
    }else if (indexPath.row == 1){
        cell.centerTF.userInteractionEnabled = NO;
        cell.centerTF.text = _protectionName;
        
    }else if (indexPath.row == 2){
        cell.centerLabel.hidden = NO;
        cell.centerTF.hidden = YES;
        if (self.configNames.count != 0) {
            NSString *string = [self.configNames componentsJoinedByString:@","];
            cell.centerLabel.text = string;
            
        }else{
            cell.centerLabel.text = @"";
            
        }
        
    }else if (indexPath.row == 3){
        cell.centerTF.userInteractionEnabled = NO;
        cell.centerTF.text = _oilType;
        
        
    }else if (indexPath.row == 4){
        cell.centerTF.userInteractionEnabled = NO;
        cell.rightImage.hidden = YES;
        cell.switchButton.hidden = NO;
        [cell.switchButton setOn:is4S];
        
    }else if (indexPath.row == 5){
        cell.centerTF.userInteractionEnabled = YES;
        cell.rightImage.hidden = YES;
        cell.centerTF.placeholder = @"请输入瑕疵描述";
        
    }else if (indexPath.row == 6){
        cell.centerTF.userInteractionEnabled = YES;
        cell.rightImage.hidden = YES;
        cell.centerTF.placeholder = @"请输入卖点描述";
        
    }else if (indexPath.row == 9){
        
        cell.centerTF.userInteractionEnabled = NO;
        cell.centerTF.text = _staffName;
        cell.rightImage.hidden = NO;
        cell.centerTF.placeholder = @"请选择销售人员";
        
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    
    if (indexPath.row == 0) {
        CarPictureSubmitVC *pictureVc = [[CarPictureSubmitVC alloc] init];
        pictureVc.carID = self.carID;
//        pictureVc.infomodel = self.infomodel;
        [self.navigationController pushViewController:pictureVc animated:YES];
    }else if (indexPath.row == 1){
        
        [self creatChoose:self.environOptions tag:0];
    }else if (indexPath.row == 2){
        CarConfigChooseVC *configVc = [[CarConfigChooseVC alloc] init];
        configVc.listArray = self.listArray;
        configVc.configIds = self.configIds;
        configVc.configNames = self.configNames;
        
//        configVc.infomodel = self.infomodel;
        kSelfWeak;
        configVc.configBlock = ^(NSMutableArray *configIds, NSMutableArray *configNames) {
            weakSelf.configIds = configIds;
            weakSelf.configNames = configNames;
            [weakSelf.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        };
        
        [self.navigationController pushViewController:configVc animated:YES];
    }else if (indexPath.row == 3){
        
        NSMutableArray *array = [[NSMutableArray alloc] initWithArray:self.baseCarFuelOptions];
        [self creatChoose:array tag:1];
        
    }else if (indexPath.row == 4){
        if (is4S == NO) {
            is4S =YES;
        }else{
            is4S = NO;
        }
        
        [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (indexPath.row == 9){
        
        [self LoadStaffInfo];
        
    }
}



//单个信息
-(void)creatChoose:(NSMutableArray *)titles tag:(NSInteger)tag{
    
    
    PickCustomView *pickerSingle = [[PickCustomView alloc]init];
    pickerSingle.tag = tag;
    
    pickerSingle.pickerViewHeight = 300;
    [pickerSingle setDataArray:titles];
    [pickerSingle setDefalutSelectRowStr:titles[0]];
    [pickerSingle setDelegate:self];
    [pickerSingle show];
    [self.view endEditing:YES];
}
-(void)customPickView:(PickCustomView *)customPickView selectedTitle:(NSString *)selectedTitle index:(NSInteger)index{
    
    if (customPickView.tag == 0) {
        _protectionName = selectedTitle;
        [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 1){
        _oilType = selectedTitle;
        [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 2){
        UserModel *model = self.userArray[index];
        self.saleUserId= model.userId;
        _staffName = selectedTitle;
        [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:9 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

        
    }
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 5) {
        _flawDesc = textField.text;
    }else if (textField.tag == 6){
        _sellingPointDesc = textField.text;
    }
    
}

//获取员工
-(void)LoadStaffInfo{
    
    
    NSDictionary *params = @{@"shopId":self.shopId,
                             @"marketId":self.marketId
                             };
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,staffInfoApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.userArray removeAllObjects];
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            NSMutableArray *userNames= [[NSMutableArray alloc] init];
            for (NSDictionary *dic  in array) {
                UserModel *model = [[UserModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.userArray addObject:model];
                [userNames addObject:model.userName];
                
            }
            [self creatChoose:userNames tag:2];
        }
        [SVProgressHUD dismiss];
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}

-(void)rightItemClick{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    
    [self updateCarInfo];
    
    
}
//修改车辆信息
-(void)updateCarInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,updataCarApi];
    NSArray *imageArray =@[    @{
                                   @"imageKey": @"control_booth",
                                   @"imageUrl":[IamgeFactory sharedMemory].control_booth ? [IamgeFactory sharedMemory].control_booth : @"",
                                   @"imageSeq":@"5"
                                   
                                   },
                               @{
                                   @"imageKey":@"driving_seat",
                                   @"imageUrl":[IamgeFactory sharedMemory].driving_seat ?[IamgeFactory sharedMemory].driving_seat : @"",
                                   @"imageSeq":@"4"
                                   },
                               @{
                                   @"imageKey":@"engine_bay",
                                   @"imageUrl":[IamgeFactory sharedMemory].engine_bay ? [IamgeFactory sharedMemory].engine_bay : @"",
                                   @"imageSeq":@"8"
                                   
                                   },
                               @{
                                   @"imageKey":@"insurance",
                                   @"imageUrl":[IamgeFactory sharedMemory].insurance ? [IamgeFactory sharedMemory].insurance : @"",
                                   @"imageSeq":@"11"
                                   },
                               @{
                                   @"imageKey":@"left_anterior",
                                   @"imageUrl":[IamgeFactory sharedMemory].left_anterior ? [IamgeFactory sharedMemory].left_anterior : @"",
                                   @"imageSeq":@"1"
                                   },
                               @{
                                   
                                   @"imageKey":@"odograph",
                                   @"imageUrl":[IamgeFactory sharedMemory].odograph ? [IamgeFactory sharedMemory].odograph : @"",
                                   @"imageSeq":@"6"
                                   },
                               @{
                                   @"imageKey":@"open_trunk",
                                   @"imageUrl":[IamgeFactory sharedMemory].open_trunk ? [IamgeFactory sharedMemory].open_trunk : @"",
                                   @"imageSeq":@"7"
                                   },
                               @{
                                   @"imageKey":@"registration_license",
                                   @"imageUrl":[IamgeFactory sharedMemory].registration_license ? [IamgeFactory sharedMemory].registration_license : @"",
                                   @"imageSeq":@"12"
                                   },
                               @{
                                   
                                   @"imageKey":@"right_rear",
                                   @"imageUrl":[IamgeFactory sharedMemory].right_rear ? [IamgeFactory sharedMemory].right_rear : @"",
                                   @"imageSeq":@"3"
                                   
                                   },
                               @{
                                   @"imageKey":@"gear_lever",
                                   @"imageUrl":[IamgeFactory sharedMemory].gear_lever ? [IamgeFactory sharedMemory].gear_lever : @"",
                                   @"imageSeq":@"9"
                                   },
                               @{
                                   @"imageKey": @"tyre",
                                   @"imageUrl":[IamgeFactory sharedMemory].tyre ? [IamgeFactory sharedMemory].tyre : @"",
                                   @"imageSeq":@"10"
                                   },
                               @{
                                   @"imageKey":@"vehicle_license",
                                   @"imageUrl":[IamgeFactory sharedMemory].vehicle_license ? [IamgeFactory sharedMemory].vehicle_license : @"",
                                   @"imageSeq":@"13"
                                   },
                               @{
                                   @"imageKey":@"vin",
                                   @"imageUrl":[IamgeFactory sharedMemory].vin ? [IamgeFactory sharedMemory].vin : @"",
                                   @"imageSeq":@"2"
                                   }];
    NSDictionary *params = @{
                             @"shopId":self.shopId,
                             @"carId":self.carID,
                             @"carImageJson":[imageArray toJSONString],
                             @"carEnviron":_protectionName ,
                             @"carFuel":_oilType,
                             @"car4sUpkeepState":@(is4S),
                             @"carFlawDesc":_flawDesc,//瑕疵
                             @"carSellingPointDesc":_sellingPointDesc,//卖点
                             @"carConfIds":[self.configIds componentsJoinedByString:@","],//配置
                             @"carExtendedWarranty":@(_carExtendedWarranty),
                             @"carFinanceService":@(_carFinanceService),
                             @"saleUserId":_saleUserId,
                             
                             };
        
    [SVProgressHUD show];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            [ShowMessage showHintMessage:@"车辆录入成功" duration:2.0 withRemindId:remindSuccess];
            [IamgeFactory reset];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];

        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];
        }
        [SVProgressHUD dismiss];

    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}

-(void)loadCarConfigInfo{
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,getCarCongApi] refreshRequest:YES cache:NO params:@{@"carId":self.carID} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        GetCarConfModel *configInfo = [GetCarConfModel mj_objectWithKeyValues:response];
        if (configInfo.code == 1) {
            for (NSDictionary *dic in configInfo.result) {
                confResult *child = [confResult mj_objectWithKeyValues:dic];
                [self.listArray addObject:child];
                
                for ( NSDictionary *dic1 in child.childCarConf) {
                    Childcarconfig *childInfo = [Childcarconfig mj_objectWithKeyValues:dic1];
                    if (childInfo.selectedState == YES) {
                        [self.configIds addObject:[NSString stringWithFormat:@"%zd",childInfo.confId]];
                        [self.configNames addObject:childInfo.confName];
                    }
                    
                }
                
            }
            
            [self.tableview reloadData];
        }
        
        [SVProgressHUD dismiss];

    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableview.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.tableview.contentInset = UIEdgeInsetsZero;
    
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    if ([eventName isEqualToString:@"ISYES"]) {
        if (index.row == 7) {
            self.carFinanceService = 1;
        }else if (index.row == 8){
            self.carExtendedWarranty = 1;
        }
        
    }else if ([eventName isEqualToString:@"ISNO"]){
        if (index.row == 7) {
            self.carFinanceService = 0;
        }else if (index.row == 8){
            self.carExtendedWarranty = 0;
        }
    }
    [self.tableview reloadData];
    
}

@end
